/**
 * 
 */
package cn.electronic.sale.controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;

import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author nightingale
 *
 */
@Controller
@RequestMapping("link")
public class LinkController extends BasicController {
	@RequestMapping("test")
	public String LinkDemo()
	{	
		System.out.println("test");
		return "link/contact";
		
	}
	@RequestMapping("response")
	public @ResponseBody String LinkDemo2(HttpServletRequest request) throws IOException
	{
		String info = request.getParameter("info");
		String question = new String(info.getBytes("ISO-8859-1"),"utf-8");
		String APIKEY = request.getParameter("key");
		System.out.println("success");
		//String APIKEY = "96625c3189f54aafa043ea2db59d0e36";
		//String question = "你叫什么名字";//这是上传给云机器人的问题
		try {
			String INFO = URLEncoder.encode(question, "utf-8");
			 String getURL = "http://www.tuling123.com/openapi/api?key=" + APIKEY + "&info=" + INFO;
			 URL getUrl = new URL(getURL);
			 HttpURLConnection connection = (HttpURLConnection) getUrl.openConnection(); 
		     connection.connect(); 
		        
		        
		     // 取得输入流，并使用Reader读取 
		        BufferedReader reader = new BufferedReader(new InputStreamReader( connection.getInputStream(), "utf-8")); 
		        StringBuffer sb = new StringBuffer(); 
		        String line = ""; 
		        int i = 0;
		        while ((line = reader.readLine()) != null) { 
		            sb.append(line); 
		            i++;
		        } 
		        reader.close();    
		        
		        // 断开连接 
		        connection.disconnect(); 
		        System.out.println(sb); 
		        String sb1 = sb.toString();
		    	return sb1;    
		        
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		return null;
		
		
	}
}
